package ch.bfh.mobicomp.soda2.magnetometer;

import ch.bfh.mobicomp.soda2.magnetometer.utils.SharedPreferencesManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.Log;

public class ControlUnitService extends Service {

	private PowerManager.WakeLock wakelock;
	private SharedPreferencesManager storage;
	private MagnetoListener measureListener;
	
	@Override
	public void onCreate() {
		super.onCreate();
		
		PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
		wakelock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DoTurnOfTheScreen");
		
		storage = new SharedPreferencesManager(this);
		
		measureListener = new MagnetoListener(this);
		Log.d(MainActivity.LOG_TAG, "Create ControlUnit");
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		startMeasuring();
		return super.onStartCommand(intent, flags, startId);
	}
	
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public void onDestroy() {
		stopMeasuring();
		super.onDestroy();
	}
	
	public void stopMeasuring() {
		wakelock.release();
		storage.putBoolean(SharedPreferencesManager.KEY_IS_MEASURING, false);
		measureListener.onStopListening();
	}
	
	public void startMeasuring() {
		wakelock.acquire();
		storage.putBoolean(SharedPreferencesManager.KEY_IS_MEASURING, true);
		measureListener.onStartListening();
		Log.d(MainActivity.LOG_TAG, "start Measuring");
	}

}
